<template>
  <div>
    <div class="headline"><van-nav-bar
  title="搜索"
/></div>
<van-search v-model="value" 
@input="searchInputFn"
placeholder="请输入搜索关键词" />

<div>
  <div v-if="resultList.length===0">
  <p class="ren">热门搜索</p>
  <van-row gutter="20">
  <van-col span="8" v-for="(item,index) in hotList" :key="index"
  @click="fn(item.first)"
  >{{item.first}}</van-col>
 
</van-row>
</div>
<div v-else>
<p class="title">最佳匹配</p>
<van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
>
  <van-cell
        center
        v-for="obj in resultList"
        :key="obj.id"
        :title="obj.name"
        @click="toPage(obj.id)"
        :label="obj.ar[0].name + ' - ' + obj.name"
      >
        <template #right-icon>
          <van-icon name="play-circle-o" size="0.6rem"/>
        </template>
      </van-cell>
      </van-list>
      </div>
</div>
  </div>
</template>

<script>
import {hotSearchAPI,searchResultAPI} from "../../api/index"
export default {
data(){
  return{
    value:'',
    hotList:[],
     resultList: [],
     loading: false,
      finished: false,
      page:1
  }
},
async created(){
  const res =await hotSearchAPI();
 
  this.hotList=res.data.result.hots
 
 
},
methods:{
 async search(){
   return await searchResultAPI({
        keywords: this.value,
        limit: 20,
        offset: (this.page - 1) * 20, // 固定公式
      }); // 把搜索结果return出去
  },
  async fn(val){
    this.page=1
    this.value=val
  let res=await this.search()
  this.resultList= res.data.result.songs;
 
  } ,
  async onLoad(){
      this.page++;
      let res = await this.search()
      if(res.data.result.songCount == 0){
        // 判断无数据的情况
        this.finished = true;
        return
      }
      this.resultList = [...this.resultList,...res.data.result.songs];

      this.loading = false;
    },
 async searchInputFn(){
   this.page=1
   let res=await this.search()
   this.resultList=res.data.result.songs;
 },
 toPage(id){
   this.$router.push({
     path:"/play",
     query:{
       id
     }
   })
 }
  
}
}
</script>

<style scoped>
.ren{
  font-size: 16px;
  padding: 10px;
}
.van-col{
 height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  font-size: 18px;
  text-align: center;
  line-height: 40px;
}
.title{
  font-size: 16px;
  padding: 10px;
}
</style>